<template>
  <a-select
    v-model:value="state.value"
    mode="multiple"
    placeholder="邮箱搜索"
    style="width: 100%"
    :mask="false"
    :filter-option="false"
    :not-found-content="state.fetching ? undefined : null"
    :options="state.data"
    @search="fetchUser"
    @change="change"
  >
    <template v-if="state.fetching" #notFoundContent>
      <a-spin size="small" />
    </template>
  </a-select>
</template>
<script lang="ts" setup>
import { reactive, watch, defineEmits } from 'vue';
import { debounce } from 'lodash-es';
import { queryUserList } from '@/views/userManager/service';
let lastFetchId = 0;

const emit = defineEmits(['change']);

const state = reactive({
  data: [],
  value: [],
  fetching: false,
});

const fetchUser = debounce(email => {
  lastFetchId += 1;
  const fetchId = lastFetchId;
  state.data = [];
  state.fetching = true;
  const params = {
    pageNum: 1,
    pageSize: -1,
    email
  }
  queryUserList(params).then(res => {
    if (fetchId !== lastFetchId) {
        // for fetch callback order
        return;
    }
    if (res.success) {
        const data = res.data.records.map(d => {
            return {
              label: d.username,
              value: d.id,
              ...d
            };
        });
        state.data = data;
        state.fetching = false;
    }
  })
}, 300);

const change = (_, selectedOptions) => {
  const users = selectedOptions.map(option => {
    const { email: userMail, username, userPhone, id } = option
    return {
      id,
      userId: id,
      userMail,
      username,
      userPhone,
    }
  })
  emit('change', users);
}

watch(state.value, () => {
  state.data = [];
  state.fetching = false;
});
</script>

